package com.hinnotek.amoeba.ui.activity.old

import android.os.Bundle
import android.view.View
import androidx.activity.viewModels
import com.chad.library.adapter.base.BaseQuickAdapter
import com.lee.common.base.BaseActivity
import com.hinnotek.amoeba.R
import com.hinnotek.amoeba.adapters.old.SellPurchaseRequisitionAdapter
import com.hinnotek.amoeba.bean.old.SellPurchaseRequistionBean
import com.hinnotek.amoeba.databinding.IncludeRecyclerviewButtonBinding
import com.hinnotek.amoeba.dialog.CustomDialog
import com.hinnotek.amoeba.ext.init
import com.hinnotek.amoeba.utilities.IntentUtils
import com.lee.common.utils.SharedPreUtils
import com.hinnotek.amoeba.utilities.StatusBarUtil
import com.hinnotek.amoeba.utilities.ToastUtils
import com.hinnotek.amoeba.viewmodels.AmibaViewModel
import com.lee.common.network.getRequestBody
import com.lee.common.network.net.ObserverState
import com.scwang.smart.refresh.layout.api.RefreshLayout
import dagger.hilt.android.AndroidEntryPoint

@AndroidEntryPoint
class SellPurchaseRequisitionActivity : BaseActivity<IncludeRecyclerviewButtonBinding>() {
    private var mAdapter: SellPurchaseRequisitionAdapter? = null
    private var pageNo = 1
    private val pageSize = 20
    private var purchaseTypeTo: String? = null

    private val viewModel by viewModels<AmibaViewModel>()


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setLeftVisible(true)
        setTitle("采购申请")

        setContentView(R.layout.include_recyclerview_button)
    }

    override fun initVew() {

        StatusBarUtil.setStatusBarColor(this, R.color.colorbtns)
        bindingView.recyclerView.init()
        bindingView.recyclerView.adapter = SellPurchaseRequisitionAdapter().also { mAdapter = it }
        mAdapter?.setOnItemClickListener { adapter: BaseQuickAdapter<*, *>, view: View?, position: Int ->
            val bean = adapter.getItem(position) as SellPurchaseRequistionBean
            val bundle = Bundle()
            bundle.putInt("amibaPurchaseId", bean.amibaPurchaseId)
            bundle.putString("purchase_type_to", purchaseTypeTo)
            IntentUtils.startActivity(
                mContext,
                SellPurchaseRequisitionDetailActivity::class.java,
                bundle
            )
        }
        findViewById<View>(R.id.superButton_b).setOnClickListener {
            val bundle = Bundle()
            bundle.putString("purchase_type_to", purchaseTypeTo)
            IntentUtils.startActivity(
                mContext,
                SellPurchaseRequisitionAddActivity::class.java,
                bundle
            )
        }
    }

    override fun setData() {

        //下拉刷新
        bindingView.refreshLayout.setOnRefreshListener { refreshLayout: RefreshLayout ->
            refreshLayout.layout.postDelayed(
                {
                    pageNo = 1
                    getAmibaPurchaseType1ByUserId()
                    refreshLayout.finishRefresh()
                }, 0
            )
        }
        //上拉加载
        bindingView.refreshLayout.setOnLoadMoreListener { refreshLayout: RefreshLayout ->
            refreshLayout.layout.postDelayed(
                {
                    pageNo++
                    getAmibaPurchaseType1ByUserId()
                    refreshLayout.finishLoadMore()
                }, 0
            )
        }
        purchaseTypeTo = intent.getStringExtra("purchase_type_to")
        mAdapter?.setPurchase_type_to(purchaseTypeTo)
    }

    override fun onResume() {
        super.onResume()
        bindingView.refreshLayout.autoRefresh() //第一次进入触发自动刷新，演示效果
    }//将不会再次触发加载更多事件//setNoMoreData(false);

    /**
     * app端获取某个阿米巴销售用户的采购申请单分页数据接口
     */
    private fun getAmibaPurchaseType1ByUserId() {

        val customDialog = CustomDialog(mContext, "正在加载...")
        customDialog.show()
        val userId = SharedPreUtils.getInteger("userId", 0)
        val map = mutableMapOf<String, Any>().apply {
            put("userId", userId)
            put("pageNo", pageNo)
            put("pageSize", pageSize)
        }

        if (purchaseTypeTo == "market") {
            viewModel.getAmibaPurchaseType1ByUserId(getRequestBody(map))
                .observe(this, object : ObserverState<MutableList<SellPurchaseRequistionBean>>() {
                    override fun onDataChange(data: MutableList<SellPurchaseRequistionBean>) {
                        customDialog.dismiss()
                        handleData(data)
                        super.onDataChange(data)
                    }

                    override fun onError(msg: String?, code: Int) {
                        customDialog.dismiss()
                        ToastUtils.showShort(mContext, msg)
                        super.onError(msg, code)
                    }
                })
        }
        else if (purchaseTypeTo == "technology"){
            viewModel.getAmibaPurchaseType2ByUserId(getRequestBody(map))
                .observe(this, object : ObserverState<MutableList<SellPurchaseRequistionBean>>() {
                    override fun onDataChange(data: MutableList<SellPurchaseRequistionBean>) {
                        customDialog.dismiss()
                        handleData(data)
                        super.onDataChange(data)
                    }

                    override fun onError(msg: String?, code: Int) {
                        customDialog.dismiss()
                        ToastUtils.showShort(mContext, msg)
                        super.onError(msg, code)
                    }
                })
        }
        else if (purchaseTypeTo == "rD"){
            viewModel.getAmibaPurchaseType3ByUserId(getRequestBody(map))
                .observe(this, object : ObserverState<MutableList<SellPurchaseRequistionBean>>() {
                    override fun onDataChange(data: MutableList<SellPurchaseRequistionBean>) {
                        customDialog.dismiss()
                        handleData(data)
                        super.onDataChange(data)
                    }

                    override fun onError(msg: String?, code: Int) {
                        customDialog.dismiss()
                        ToastUtils.showShort(mContext, msg)
                        super.onError(msg, code)
                    }
                })
        }
    }

    fun handleData(data: MutableList<SellPurchaseRequistionBean>) {
        if (pageNo == 1) {
            when (getRefreshStatus(data.size)) {
                Status.SUCCESS -> {
                    mAdapter?.setList(data)
                    if (data.size < pageSize) {
                        bindingView.refreshLayout.setEnableLoadMore(false)
                    } else {
                        bindingView.refreshLayout.setEnableLoadMore(true)
                    }
                    bindingView.refreshLayout.resetNoMoreData() //setNoMoreData(false);
                    bindingView.llStateful.showContent()
                }
                Status.EMPTY -> {
                    bindingView.llStateful.showEmpty()
                    bindingView.refreshLayout.setEnableLoadMore(false)
                }
                Status.ERROR -> showError()
                Status.NO_NET -> showOffline()
            }
            bindingView.refreshLayout.finishRefresh()
        } else {
            if (data.size == 0) {
                ToastUtils.showShort("数据全部加载完毕")
                bindingView.refreshLayout.finishLoadMoreWithNoMoreData() //将不会再次触发加载更多事件
            } else {
                mAdapter?.addData(data)
                bindingView.refreshLayout.finishLoadMore()
            }
        }

    }

    private fun showOffline() {
        bindingView.llStateful.showOffline { v: View? -> bindingView.refreshLayout.autoRefresh() }
        bindingView.refreshLayout.setEnableLoadMore(false)
    }

    private fun showError() {
        bindingView.llStateful.showError(View.OnClickListener { v: View? -> bindingView.refreshLayout.autoRefresh() })
        bindingView.refreshLayout.setEnableLoadMore(false)
    }

    private enum class Status {
        SUCCESS, EMPTY, ERROR, NO_NET
    }

    private fun getRefreshStatus(size: Int): Status {
        return if (size == 0) {
            Status.EMPTY
        } else Status.SUCCESS
    }
}